package cn.yutong.framework;

import com.google.common.collect.Maps;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.logging.Logger;

@Component
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling
public class UserCache {
    // 已经登录用户数据缓存
    private static Map<Integer, CacheUser> allUserMap = Maps.newHashMap();

    public static Map<Integer, CacheUser> getAllUserMap() {
        return allUserMap;
    }


    public static CacheUser getUser(Integer userid) {
//        CacheUser user =;
//        if (user!=null) touchUser(userid);
        return  allUserMap.get(userid);
    }

    public static void add2UserMap(Integer userID) {
        CacheUser user = new CacheUser();
        user.setUid(userID);
        user.setLastHitTime(System.currentTimeMillis());
        allUserMap.put(userID, user);
    }

    public static void touchUser(Integer userID) {
        CacheUser user = getUser(userID);
        user.setLastHitTime(System.currentTimeMillis());
        allUserMap.put(userID, user);
    }

    public static void clear() {
        allUserMap.clear();
    }

    public static void clearOne(Integer id) {
        allUserMap.remove(id);
    }

    @Scheduled(cron = "0/5 * * * * ?")
    public void cleanCache() {
        for (Map.Entry<Integer, CacheUser> entry : allUserMap.entrySet()) {
            Integer userID = entry.getKey();
            CacheUser user = entry.getValue();
            long time = System.currentTimeMillis() - user.getLastHitTime();
//            if (time > 10 * 1000) {
            if (time > 30 * 60 * 1000) {
                allUserMap.remove(userID);
                Logger.getLogger(UserCache.class.getSimpleName()).info("用户缓存清理:[" + userID + "]");
            }
        }
    }

}
